<template>
  <div class="gobang-bg">
    <div class="reg-container">
      <h2 class="reg-title">用户注册</h2>
      <form class="reg-form" @submit.prevent="register">
        <input ref="usernameRef" type="text" placeholder="用户名" class="reg-input" v-model="username"
          autocomplete="username" @keydown.enter.prevent="focusNext('pwdRef')" />
        <input ref="pwdRef" type="password" placeholder="密码" class="reg-input" v-model="pwd"
          autocomplete="current-password" @keydown.enter.prevent="focusNext('pwd2Ref')" />
        <input ref="pwd2Ref" type="password" placeholder="确认密码" class="reg-input" v-model="pwd2"
          @keydown.enter.prevent="focusNext('phoneRef')" />
        <input ref="phoneRef" type="text" placeholder="手机号" class="reg-input" v-model="phone"
          @keydown.enter.prevent="register" />

        <div class="reg-row-flex">
          <div class="reg-gender-radio" ref="genderRef">
            <label>
              <input type="radio" value="1" v-model="gender" @keydown.enter.prevent="register" /> 男
            </label>
            <label>
              <input type="radio" value="0" v-model="gender" @keydown.enter.prevent="register" /> 女
            </label>
            <div class="reg-avatar-group">
              <label class="reg-avatar-upload">
                <input type="file" class="reg-avatar-input" @change="onAvatarChange" accept="image/*" ref="avatarRef"
                  @keydown.enter.prevent="register" />
                <div class="reg-avatar-circle">
                  <template v-if="avatarUrl">
                    <img :src="avatarUrl" class="reg-avatar-img" alt="头像预览" />
                  </template>
                  <template v-else>
                    <span class="reg-avatar-plus">+</span>
                  </template>
                </div>
              </label>
            </div>
          </div>
        </div>
        <button type="submit" class="reg-btn" :disabled="loading">{{ loading ? '注册中...' : '注册' }}</button>
        <div class="login-read">
          <input type="checkbox" id="read" name="read" v-model="read" />
          <label for="read" class="login-link-read">阅读并同意<a href="/login/protocol">《用户协议》</a>和<a
              href="/login/protocol">《隐私条款》</a></label>
        </div>
        <a href="/login" class="reg-link">
          <span class="reg-login-tip">已有账号？</span>
          去登录
        </a>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref,onMounted } from 'vue'
import useNetStore from '../stores/net.js'
import md5 from 'blueimp-md5'
const net = useNetStore()

const username = ref('')
const pwd = ref('');
const pwd2 = ref('');
const gender = ref('');
const phone = ref('');
const avatar = ref('');
const avatarFile = ref(null)
const avatarUrl = ref('')
const loading = ref(false)
const read = ref(false)

const usernameRef = ref(null)
const pwdRef = ref(null)
const pwd2Ref = ref(null)
const genderRef = ref(null)
const avatarRef = ref(null)
const phoneRef = ref(null)

onMounted(() => {
  // 自动聚焦到用户名输入框
  usernameRef.value.focus()
})

function focusNext(refName) {
  if (refName === 'usernameRef' && usernameRef.value) {
    usernameRef.value.focus()
  } else if (refName === 'pwdRef' && pwdRef.value) {
    pwdRef.value.focus()
  } else if (refName === 'pwd2Ref' && pwd2Ref.value) {
    pwd2Ref.value.focus()
  } else if (refName === 'phoneRef' && phoneRef.value) {
    phoneRef.value.focus()
  } else if (refName === 'avatarRef' && avatarRef.value) {
    avatarRef.value.focus()
  } else if (refName === 'genderRef' && genderRef.value) {
    genderRef.value.focus()
  } else if (refName === 'submitRef') {
    submitRef.value.focus()
  }
}

const onAvatarChange = (e) => {
  const file = e.target.files[0]
  avatarFile.value = file || null
  if (file) {
    avatarUrl.value = URL.createObjectURL(file)
    avatar.value = file // 这里保存原始文件用于上传
  } else {
    avatarUrl.value = ''
    avatar.value = ''
  }
}

// 手机号简单校验
function isPhone(str) {
  return /^1[3-9]\d{9}$/.test(str)
}

// 注册功能
const register = async () => {
  if (loading.value) return
  if (!username.value.trim()) {
    focusNext('usernameRef')
    return alert('用户名不能为空')
  }
  if (!pwd.value) {
    focusNext('pwdRef')
    return alert('密码不能为空')
  }
  if (pwd.value.length < 6) {
    focusNext('pwdRef')
    return alert('密码不能少于6位')
  }
  if (pwd.value !== pwd2.value) {
    focusNext('pwd2Ref')
    return alert('两次输入的密码不一致')
  }
  if (!gender.value) {
    focusNext('genderRef')
    return alert('请选择性别')
  }
  if (!phone.value) {
    focusNext('phoneRef')
    return alert('请输入手机号')
  }

  if (phone.value == '' && !isPhone(phone.value)) {
    focusNext('phoneRef')
    return alert('手机号格式不正确')
  }
  if (read.value === false) {
    return confirm("是否勾选选用户协议和隐私条款？") ? read.value = true : false
  }
  loading.value = true

  // 构造 FormData 用于文件上传
  const formData = new FormData()
  formData.append('username', username.value)
  const encryptedPwd = md5(pwd.value)
  formData.append('pwd', encryptedPwd)
  formData.append('gender', gender.value)
  formData.append('phone', phone.value)
  formData.append('avatar', avatar.value) // 这里传文件

  try {
    const res = await net.fasong(formData, '/users/reg', {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    if (res.code === 200) {      
      window.location.href = '/userId?username='+username.value
      username.value = ''
      pwd.value = ''
      pwd2.value = ''
      gender.value = ''
      phone.value = ''
      avatar.value = ''
      avatarUrl.value = ''
    } else {
      alert(res.msg || '注册失败')
    }
  } catch (err) {
    alert('用户名重复，请重新输入')
    username.value = ''
    // console.log(err)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
/* 动态棋盘背景 */
.gobang-bg {
  min-height: 100vh;
  min-width: 100vw;
  background:
    /* repeating-linear-gradient(45deg, rgb(254, 254, 254) 0 40px, rgba(255, 255, 255, 0.1) 40px 80px); */
    repeating-linear-gradient(135deg, rgb(226, 192, 168) 0px 40px, rgba(255, 255, 255, 1) 40px 80px);
  /* background: #f9c3c3; */
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 注册框 */
.reg-container {
  position: relative;
  width: 470px;
  padding: 48px 36px 36px 36px;
  border-radius: 22px;
  background: rgba(255, 255, 255, 0.25);
  box-shadow: 0 8px 32px 0 rgba(60, 60, 60, 0.18);
  backdrop-filter: blur(12px);
  border: 1.5px solid rgba(255, 255, 255, 0.35);
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 标题 */
.reg-title {
  margin-bottom: 32px;
  color: #222;
  font-weight: 700;
  font-size: 28px;
  letter-spacing: 2px;
  text-shadow: 0 2px 8px rgba(255, 255, 255, 0.2);
}

/* 表单 */
.reg-form {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

/* 输入框 */
.reg-input,
.reg-gender-radio {
  padding: 14px 16px;
  border: 1.5px solid #e0e0e0;
  border-radius: 10px;
  font-size: 16px;
  background: rgba(255, 255, 255, 0.3);
  transition: border-color 0.2s, box-shadow 0.2s;
  outline: none;
  box-shadow: 0 1px 4px rgba(64, 158, 255, 0.04);
}

.reg-input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.12);
  background: #fff;
}

/* 性别单选 */
.reg-gender-radio {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 18px;
  min-width: 120px;
  flex: 1 1 0;
  padding: 5px;
  background: rgba(255, 255, 255, 0.3);

}

.reg-gender-radio label:first-child {
  margin-left: 50px;
}

.reg-gender-radio label {
  font-size: 16px;
  color: #555;
  margin-right: 10px;
  cursor: pointer;
}

.reg-gender-radio input[type="radio"] {
  margin-right: 4px;
  accent-color: #409eff;
  transform: scale(1.15);
}

/* 头像上传 */
.reg-avatar-group {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 0;
}

.reg-avatar-label {
  color: #333;
}

.reg-avatar-upload {
  position: relative;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.reg-avatar-input {
  opacity: 0;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  cursor: pointer;
  z-index: 2;
}

.reg-avatar-circle {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background: #f5f7fa;
  border: 2px dashed #409eff;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  transition: border-color 0.2s;
  overflow: hidden;
}

.reg-avatar-upload:hover .reg-avatar_circle {
  border-color: #67c23a;
}

.reg-avatar-plus {
  font-size: 36px;
  color: #bfbfbf;
  font-weight: bold;
  user-select: none;
}

.reg-avatar-img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  border: none;
}

/* 注册按钮 */
.reg-btn {
  padding: 14px;
  background: linear-gradient(90deg, #409eff 0%, #67c23a 100%);
  color: #fff;
  border: none;
  border-radius: 10px;
  font-size: 17px;
  font-weight: 600;
  cursor: pointer;
  letter-spacing: 2px;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.08);
  transition: background 0.4s cubic-bezier(.4, 0, .2, 1),
    box-shadow 0.4s cubic-bezier(.4, 0, .2, 1),
    color 0.4s cubic-bezier(.4, 0, .2, 1);
}

.reg-btn:hover {
  background: linear-gradient(90deg, #67c23a 0%, #409eff 100%);
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.15);
  color: #222;
}



/* 阅读协议 */
.login-read {
  margin-top: 10px;
  margin-right: 98px;
  color: #666 !important;
}

#read {
  margin-right: 10px;
  cursor: pointer;
  transform: scale(1.2);
}

/* 去登录链接 */
.reg-link,
.login-read {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 10px;
  color: #409eff;
  font-size: 15px;
  text-decoration: none;
  gap: 4px;
  transition: color 0.2s;
}

.reg-link:hover {
  color: #67c23a;
  text-decoration: underline;
}

.reg-login-tip {
  color: #666;
  font-size: 14px;
}

/* 行内元素间距 */
.reg-row-flex {
  display: flex;
  align-items: center;
  gap: 32px;
  margin-bottom: 10px;
}
</style>